package com.example.foods.service.impl;

import com.example.foods.data.CategoryMapper;
import com.example.foods.data.FoodCategoryMapper;
import com.example.foods.domain.CategoryInfo;
import com.example.foods.entity.Category;
import com.example.foods.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional //该类中的所有方法，都需要进行事务控制
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private FoodCategoryMapper foodCategoryMapper;

    @Transactional(readOnly = true)
    @Override
    public CategoryInfo findByCatName(String catName) {
        CategoryInfo categoryInfo = null;
        Category category = this.categoryMapper.findByCatName(catName);
        if (category != null) {
            categoryInfo = new CategoryInfo();
            BeanUtils.copyProperties(category, categoryInfo);
        }
        return categoryInfo;
    }

    @Override
    public boolean addCategory(CategoryInfo categoryInfo) {
        //检查类别名称是否已经存在
        Category category = this.categoryMapper.findByCatName(categoryInfo.getCatName());
        if (category != null) {
            throw new RuntimeException("类别名称已经存在!");
        }
        Category category1 = new Category();
        category1.setCatName(categoryInfo.getCatName());
        category1.setCatDesc(categoryInfo.getCatDesc());
        category1.setDelFlag((short) 0);
        int count = this.categoryMapper.saveCategory(category1);
        return count > 0;
    }

    @Transactional(readOnly = true)
    @Override
    public List<CategoryInfo> findAllCategories() {
        List<Category> categories = this.categoryMapper.findAllCategories();

        List<CategoryInfo> infos = new ArrayList<>();
        CategoryInfo info;
        for (Category category : categories) {
            info = new CategoryInfo();
            BeanUtils.copyProperties(category, info);
            infos.add(info);
        }
        return infos;
    }

    @Override
    public int deleteCategories(Integer[] catId) {
        int count = this.categoryMapper.deleteCategories(catId);
        int count1 = this.foodCategoryMapper.deleteByCatId(catId);
        log.debug("从t_food_categories表中删除了" + count1 + "条记录。");
        return count;
    }
}
